/**
 * Created by Administrator on 2017/6/13.
 */

let https = require('https');
let crypto = require('crypto');
let variable = require('../data/variable.js');
let gameData = require('../util/gameData.js');
let util = require('./util.js');
let rpc = require('./rpc.js');
let log = require('./log.js');

let bluedSDK = module.exports;

bluedSDK.refresh = function (access_token, cb) {
    requestGet(access_token, '/oauth2/refresh', null, cb);
};
bluedSDK.self = function (access_token, cb) {
    requestGet(access_token, '/users/self', null, cb);
};
bluedSDK.uid = function (access_token, uid, cb) {
    requestGet(access_token, '/users/' + uid, null, cb);
};
bluedSDK.friends = function (access_token, uid, cb) {
    requestGet(access_token, '/users/' + uid + '/friends', null, cb);
};
bluedSDK.sync = function (access_token, param, cb) {
    requestPost(access_token, '/pay/goods/sync', param, cb);
};
bluedSDK.followed = function (access_token, data, cb) {
    requestPost(access_token, '/users/' + data.bluedId + '/followed/' + data.uid, null, cb);
};
bluedSDK.unFollowed = function (access_token, data, cb) {
    let param = {};
    param.http_method_override = 'DELETE';
    requestPost(access_token, '/users/' + data.bluedId + '/followed/' + data.uid, param, cb);
};
bluedSDK.status = function (access_token, operation, cb) {
    let param = {'operation': operation};
    requestGet(access_token, '/game/' + variable.blued[variable.blued.use].appKey + '/status', param, cb);
    //requestPost(access_token, '/game/' + variable.blued[variable.blued.use].appKey + '/status', param, cb);
};
bluedSDK.sum = {
    ios: function (access_token, cb) {
        requestGet(access_token, '/pay/ios/sum', null, cb);
    },
    android: function (access_token, cb) {
        requestGet(access_token, '/pay/android/sum', null, cb);
    }
};
bluedSDK.orders = {
    ios: function (access_token, goods_id, cb) {
        bluedSDK.orders.send(access_token, 'ios', goods_id, cb);
    },
    android: function (access_token, goods_id, cb) {
        bluedSDK.orders.send(access_token, 'android', goods_id, cb);
    },
    send: function (access_token, platform, goods_id, cb) {
        let param = {'goods_id': goods_id};
        requestPost(access_token, '/pay/' + platform + '/orders', param, cb);
    }
};
bluedSDK.payment = function (access_token, orders_id, payment, cb) {
    let sha1 = crypto.createHash("sha1").update(payment).digest("hex");
    let param = {'orders_id': orders_id, 'payment': sha1};
    requestPost(access_token, '/pay/goods/sync', param, cb);
};
bluedSDK.consume = {
    ios: function (access_token, orders_id, payment, cb) {
        bluedSDK.consume.send(access_token, 'ios', orders_id, cb);
    },
    android: function (access_token, orders_id, payment, cb) {
        bluedSDK.consume.send(access_token, 'android', orders_id, cb);
    },
    send: function (access_token, platform, orders_id, payment, cb) {
        let param = {'orders_id': orders_id, 'payment': payment};
        requestPost(access_token, '/pay/' + platform + '/consume', param, cb);
    }
};

bluedSDK.payUrl = function (access_token, goodsId, bodyString) {
    let T = Math.floor(Date.now() / 1000).toString();
    let blued = sign(access_token, T);
    console.log('appKey:',variable.blued[variable.blued.use].appKey);
    console.log('appSecretKey:',variable.blued[variable.blued.use].appSecretKey);
    console.log('T:',T);
    console.log('access_token:',access_token);
    console.log('sign:',blued);
    let url = 'https://common.blued.com/?action=blued_pay&goods_id=' + goodsId + '&sign=' + blued + '&t=' + T + '&token=' + access_token + '&body=' + bodyString;

    return url;
};
bluedSDK.payCallback = function (data) {
    console.log('payCallback', data);
    if (data.appid != variable.blued[variable.blued.use].appKey) {
        return 'fail1';
    }
    if (!gameData.d.goods[data.goods_id]) {
        return 'fail2';
    }
    if (gameData.d.goods[data.goods_id].beans != data.beans) {
        return 'fail3';
    }
    if (!data.body) {
        return 'fail4';
    }

    let sign = data.sign;
    delete data.sign;
    let jsonSort = util.jsonSort(data);
    let str = util.paramToUrl(jsonSort);
    let encodedSign = crypto.createHmac('sha1', variable.blued[variable.blued.use].appSecretKey).update(str).digest('').toString('base64');
    if (sign != encodedSign) {
        return 'fail5';
    }
    bluedSDK.payRequest(data);

    return 'success';
};
bluedSDK.payRequest = function (data) {
    if (data.notify_time) {
        data.notify_time = encodeURI(data.notify_time);
    }
    let param = data;
    rpc.dc.send('payCallback', param);
};
//let param = [
//    {'goods_id': 1001, 'name': 'iOS测试', 'icon': '', 'platform': 'ios', 'beans': 1, 'status': 1},
//    {'goods_id': 2001, 'name': 'android测试', 'icon': '', 'platform': 'android', 'beans': 1, 'status': 1}
//];
//blued.sync(access_tokenS, param, function (result) {
//    console.log(result);
//    let param1 = {'goods_id': 1001};
//    blued.orders.ios(access_tokenS, param1, function (result) {
//        console.log('ios:', result);
//    });
//
//    let param2 = {'goods_id': 2001};
//    blued.orders.android(access_tokenS, param2, function (result) {
//        console.log('android:', result);
//    });
//});
//blued.orders.ios(access_tokenS, 1001, function (result) {
//    console.log('ios:', result);
//    blued.consume.ios(access_tokenS, result.data[0].orders_id, function (result1) {
//        console.log('ios:', result1);
//    });
//});
//blued.orders.android(access_tokenS, 2001, function (result) {
//    console.log('android:', result);
//    blued.consume.android(access_tokenS, result.data[0].orders_id, function (result1) {
//        console.log('android:', result1);
//    });
//});

function sign(access_token, T) {
    let Tc = T.split("").reverse().join("");
    let str = access_token + Tc;
    let encodedSign = crypto.createHmac('sha1', variable.blued[variable.blued.use].appSecretKey).update(str).digest('').toString('base64');
    let __ = variable.blued[variable.blued.use].appKey + ':' + encodedSign;
    let sign = new Buffer(__).toString('base64');

    return sign;
}
function requestGet(access_token, api, param, cb) {
    let T = Math.floor(Date.now() / 1000).toString();
    let blued = sign(access_token, T);

    console.log('host:', variable.blued[variable.blued.use].host);
    console.log('appKey:', variable.blued[variable.blued.use].appKey);
    console.log('appSecretKey:', variable.blued[variable.blued.use].appSecretKey);
    console.log('T:', T)
    console.log('access_token:', access_token)
    console.log('BLUED:', blued)

    let pathAdd = '';
    if (param) {
        pathAdd = '&' + util.paramToUrl(param);
    }

    let opt = {
        hostname: variable.blued[variable.blued.use].host,
        port: 443,
        path: api + '?T=' + T + '&access_token=' + access_token + pathAdd,
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
            'authorization': 'BLUED ' + blued
        }
    };
    https.request(opt, function (res) {
        let result = '';
        res.on('data', function (data) {
            result += data;
        });
        res.on('end', function () {
            try {
                //log.d('bluedSDK get',opt,result);
                let data = JSON.parse(result);
                cb(data);
            } catch (e) {
                cb({"code": 401, 'message': e.message});
            }
        });
    }).on('error', function (e) {
        cb({"code": 400, 'message': e.message});
    }).end();
}

function requestPost(access_token, api, param, cb) {
    let T = Math.floor(Date.now() / 1000).toString();
    let blued = sign(access_token, T);

    let pathAdd = '';
    if (param && param.http_method_override) {
        pathAdd = '&http_method_override=' + param.http_method_override;
        delete param.http_method_override;
    }

    let opt = {
        hostname: variable.blued[variable.blued.use].host,
        port: 443,
        path: api + '?T=' + T + '&access_token=' + access_token + pathAdd,
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'authorization': 'BLUED ' + blued
        }
    };
    let reqHttps = https.request(opt, function (res) {
        let result = '';
        res.on('data', function (data) {
            result += data;
        });
        res.on('end', function () {
            try {
                //log.d('bluedSDK post',opt,result);
                let data = JSON.parse(result);
                cb(data);
            } catch (e) {
                cb({"code": 401, 'message': e.message});
            }
        });
    });
    reqHttps.write(JSON.stringify(param));
    reqHttps.end();
    reqHttps.on('error', function (e) {
        cb({"code": 400, 'message': e.message});
    });
}